/**
 * Created by zhoumingrui on 2017/1/17.
 */

class ObjImgPrepare{
    constructor(imageCache) {
        this.imageCache = imageCache || {};
    }

    /**
     * 这里就是加载material对应的图片的索引
     * @param collada
     */
    saveMaterial(gl, result) {
        /**
         * 获取图片
         * diffuseMap:"./DAE\\TEXTURES\\COREAREA\\ROAD\\WDL0000001.png"
         * illumMode:"2"
         * name:"VMtl0-material"
         */
        this.loadImages(gl, result.materials);

    }


    loadImages(gl, imgUrl) {
        /**
         "__TEXTURES_COREAREA_ROAD_WDL0000001_png"
         "./TEXTURES/COREAREA/ROAD/WDL0000001.png"
         */
        for (let i = 0; i < imgUrl.length; i++) {
            let id = imgUrl[i].name;
            let url = imgUrl[i].diffuseMap;
            this.saveOne(gl, url, id);
        }
    }

    getImageByImgId(id) {
        return this.imageCache[id] || document.getElementById('testImg');
    }

    bindOneImgById(gl,id){
        let imgCache = this.getImageByImgId(id);
        if(imgCache.texture){
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, imgCache.texture);
            gl.uniform1i(gl.getUniformLocation(gl.program, 'u_Sampler'), 0);
        }
    }

    saveOne(gl, src, id) {
        let image = new Image();
        let that = this;
        image.onload = function(){
            let texture = gl.createTexture();
            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, texture);

            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);

            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
            gl.uniform1i(gl.getUniformLocation(gl.program, 'u_Sampler'), 0);

            that.imageCache[id] = {
                image: image,
                texture: texture
            };
        }
        image.src = src;
    }
}

module.exports = ObjImgPrepare;